<template>
  <div class="task-detail-container" v-loading="loading || pageLoading">
    <!-- 顶部操作区 -->
    <div class="task-detail-header common-detail-header">
      <div>
        <el-button type="plain-third" v-if="editPermission" @click="handleEdit">
          <i class="iconfont icon-edit-square"></i>{{$t('common.base.edit')}}
        </el-button>
        <el-button
          type="plain-third"
          v-if="deletePermission"
          @click="handleDelete"
        >
          <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
        </el-button>
      </div>
      <div v-if="memberOperatePermission">
        <el-button v-if="pointsEnable" type="primary" @click="recharge(memberInfo, 'point')">
          {{$t('member.components.title43')}}
        </el-button>
        <el-button v-if="serviceFeeEnable"  type="primary" @click="recharge(memberInfo, 'serviceFee')">
          {{$t('member.components.title44')}}
        </el-button>
        <el-button v-if="balanceEnable"  type="primary" @click="recharge(memberInfo, 'balance')">
          {{$t('member.components.title45')}}
        </el-button>
        <el-button v-if="pointsEnable" type="primary" @click="consume(memberInfo, 'point')">
          {{$t('member.components.title54')}}
        </el-button>
        <el-button v-if="balanceEnable"  type="primary" @click="consume(memberInfo, 'balance')">
          {{$t('member.components.title55')}}
        </el-button>
      </div>
    </div>
    <!-- 通栏导航 -->
    <BaseTileLayoutTabBar
      :bar-list="bannerState.taskLayoutTabBarList"
      :now-item="bannerState.leftActiveTab"
      @changeItem="tabBarChangeItem"
      @openLayoutModal="openBaseLayoutModal"
      v-if="bannerState.taskLayout == 1"
    ></BaseTileLayoutTabBar>
    <!-- 会员详情折叠面板 -->
    <base-collapse
      class="task-detail-main-content detail-main-content"
      :show-collapse="true"
      :direction.sync="collapseDirection"
      :hidePartCollapse="hidePartCollapse"
    >
      <!-- 商品详情 -->
      <template slot="left">
        <div
          class="task-detail-main-content-left detail-main-content-left"
          v-show="collapseDirection != 'left'"
        >
          <!-- 左栏导航 -->
          <BaseTileLayoutTabBar
            :bar-list="bannerState.leftTabBarList"
            :now-item="bannerState.leftActiveTab"
            @openLayoutModal="openBaseLayoutModal"
            v-if="bannerState.taskLayout == 2"
          ></BaseTileLayoutTabBar>
          <!-- 详情 -->
          <MemberDetail v-if="bannerState.leftActiveTab == 'member-info'" :memberInfo="memberInfo" :authorizationList="authorizationList" @updatePage="reloadPage" :form-cell-count="formCellCount"/>
        </div>
        <div class="collapse-left" v-show="collapseDirection == 'left'">
          {{$t('member.components.title46')}}
        </div>
      </template>

      <!-- 动态信息 -->
      <template slot="right">
        <div
          class="task-detail-main-content-right detail-main-content-right"
          v-show="collapseDirection != 'right'"
        >
          <BaseBarV3
            :bar-list="bannerState.rightTabBarList"
            :now-item="bannerState.rightActiveTab"
            @changeItem="tabBarChangeItem"
            @upDateBarList="tabBarUpdateList"
            v-if="bannerState.taskLayout == 2"
          />
          <!-- 动态信息 -->
          <member-record v-if="bannerState.rightActiveTab=='record'" ref="memberRecord" :memberId="memberId" :collapseDirection="collapseDirection"/>
          <!-- 会员积分 -->
          <record v-if="bannerState.rightActiveTab=='pointRecord'" ref="pointRecord" :memberInfo="memberInfo" :record-type="'points'" :config="pointAddOnConfig"/>
          <!-- 会员钱包 -->
          <record v-if="bannerState.rightActiveTab=='balanceRecord'" ref="balanceRecord" :memberInfo="memberInfo" :record-type="'balance'" :config="balanceAddOnConfig"/>
          <!-- 额度记录 -->
          <limit-record v-if="bannerState.rightActiveTab=='limitRecord'" ref="limitRecord" :memberInfo="memberInfo"/>
          <!-- 服务费记录 -->
          <record v-if="bannerState.rightActiveTab=='serviceFeeRecord'" ref="serviceFeeRecord" :memberInfo="memberInfo" :record-type="'serviceFee'" :config="serviceFeeAddOnConfig"/>
        </div>
      </template>
      <template slot="rightExtend">
        <button class="right-extend-btn" @click="rightTabs = 'record'">
          <i class="iconfont icon-message1"></i>{{$t('common.base.addRemark')}}
        </button>
      </template>
    </base-collapse>
    <recharge-balance-dialog ref="rechargeBalanceDialog" @updateList="updateBalance" />
    <recharge-serviceFee-dialog ref="rechargeServiceFeeDialog" @updateList="updateServiceFee" />
    <recharge-dialog ref="rechargeDialog"  @updateList="updatePoint"/>
    <ConsumeDialog 
      ref="consumeDialogRef"
      @updateList="updateList"
    />
    <!-- 通栏设置 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="bannerState.taskLayout"
      :columns="formCellCount"
      @changeLayout="changeTaskDetailLayout">
    </biz-layout-modal>
  </div>
</template>

<script>
import _ from 'lodash';
import qs from '@src/util/querystring';
import { getMemberDetails, memberDelete, searchMemberShipAuthorization } from '@src/api/Member'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import RechargeDialog from '../components/RechargeDialog';
import RechargeBalanceDialog from '../components/RechargeBalanceDialog';
import MemberDetail from './components/MemberDetail';
import Record from './components/Record';
import LimitRecord from './components/LimitRecord';
import MemberRecord from './components/MemberRecord';
import RechargeServiceFeeDialog from '../components/RechargeServiceFeeDialog';
import { pointAddOnConfig, balanceAddOnConfig, serviceFeeAddOnConfig } from '@src/modules/member/detail/addConfiguration.js';
import AuthUtil from '@src/util/auth';
import AuthMixin from '@src/mixins/authMixin';
import memberMixin from '../mixins/memberMixin';
import AuthEnum from '@model/enum/AuthEnum.ts';
import ConsumeDialog from '@src/modules/member/components/ConsumeDialog.vue';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { computedTabList } from '@src/util/tabBarUtils'
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi'
import { cloneDeep } from 'lodash'
import { useStateSystemViewLayout } from 'pub-bbx-utils'
const { getSystemViewLayout } = useStateSystemViewLayout()
export default {
  mixins: [AuthMixin, memberMixin],
  components: {
    RechargeDialog,
    RechargeBalanceDialog,
    MemberDetail,
    RechargeServiceFeeDialog,
    Record,
    LimitRecord,
    MemberRecord,
    ConsumeDialog,
    BaseBarV3,
    BaseTileLayoutTabBar,
  },
  provide: {
    initData: {},
  },
  data() {
    return {
      pageLoading: false,
      loading: false,
      collapseDirection: '',
      leftTabs: 'detail',
      rightTabs: 'record',
      fields: [], 
      memberInfo: {},
      recordCount: 0, // 动态信息数量
      authorizationList: [],
      pointAddOnConfig,
      balanceAddOnConfig,
      serviceFeeAddOnConfig,
      bannerState: {
        taskLayout: 2, // 布局方式 1:通栏 2:左右
        leftActiveTab: '',
        leftActiveTabItem: {},
        rightActiveTab: '',
        rightActiveTabItem: {},
        tabPosition: '', // 记录tab位置  left|right
        leftTabBarList : [],
        rightTabBarList : [],
        taskLayoutTabBarList: []
      },
      formCellCount:1,
    };
  },
  computed: {
    memberId() {
      const queryObject = qs.parse(window.location.search);
      return queryObject.id ?? '';
    },
    createPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_CREATE);
    },
    editPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_EDIT);
    },
    deletePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_DELETE);
    },
    memberOperatePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_PROPERTY_OPERATE);
    },
    hidePartCollapse() {
      if(this.bannerState.taskLayout === 2) return '';

      if(this.bannerState.taskLayout === 1) {
        return this.bannerState.tabPosition === 'left' ? 'right' : 'left';
      }
    }
  },
  created() {
    this.collapseDirection =
      sessionStorage.getItem(`member_collapseDirection_${this.memberId}`) || '';
  },
  async mounted() {
    try {
      this.pageLoading = true
      await this.getEnableAuth()
      await this.initBanner()
      await this.reloadPage()
    } catch (error) {
      console.error('fetch goods Detail error', error);
    } finally {
      this.pageLoading = false;
    }
  },
  methods: {
    updatePoint() {
      this.reloadPage()
      this.$refs.memberRecord.initRecord();
      this.$refs.pointRecord.changeTab(1)
    },
    updateServiceFee() {
      this.reloadPage()
      this.$refs.memberRecord.initRecord();
      this.$refs.serviceFeeRecord.changeTab(1)
    },
    updateBalance() {
      this.reloadPage()
      this.$refs.memberRecord.initRecord();
      this.$refs.balanceRecord.changeTab(1)
    },
    updateList() {
      this.reloadPage();
      this.$refs.memberRecord.initRecord();
      this.$refs.pointRecord.changeTab(0);
      this.$refs.balanceRecord.changeTab(0);
    },
    recharge(row, type) {
      if(type == 'balance') {
        this.$refs.rechargeBalanceDialog.open(row)
      }else if(type == 'point'){
        this.$refs.rechargeDialog.open(row, type)
      }else {
        this.$refs.rechargeServiceFeeDialog.open(row, type)
      }
    },
    consume(row, type) {
      if (!row.id) return;

      this.$refs.consumeDialogRef.open(row, type);
    },
    async getMemberAuthorization() {
      // this.loading = true;
      const { code, result, message } = await searchMemberShipAuthorization({ memberShipId: this.memberId });
      if(code !== 0) return this.$message.error(message);
      this.authorizationList = result;
    },

    async reloadPage() {
      await this.getMemberAuthorization()
      await this.getMemberDetails();
      this.$refs.memberRecord.initRecord();
    },
    handleEdit() {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageMemberEdit,
        params: `id=${this.memberId}&from=detail`,
        fromId,
      });
    },
    handleDelete() {
      this.$confirm(this.$t('member.detail.title30'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(async () => {
        let idList = [this.memberId]
        const { code, message } = await memberDelete(idList);
        if(code !== 0) return this.$message.error(message);
        this.$message.success(this.$t('common.base.deleteSuccess'));

        let id = window.frameElement.dataset.id;
        this.$platform.closeTab(id);
      });
    },
    async getMemberDetails() {
      try {
        this.loading = true;

        const { code, result } = await getMemberDetails({ id: this.memberId });
        this.loading = false;
        if (code !== 0) {
          return this.$message.error(this.$t('member.edit.title3'));
        }
        this.memberInfo = result;
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    handleChangeRecordCount(num) {
      this.recordCount = num;
    },
    handleClick(tab, event) {
      const { tabName } = tab
      if(tabName == 'pointRecord') {
        this.$refs.pointRecord.changeTab(0)
      }else if (tabName == 'balanceRecord') {
        this.$refs.balanceRecord.changeTab(0)
      }else if (tabName == 'serviceFeeRecord') {
        this.$refs.serviceFeeRecord.changeTab(0)
      }else if(tabName == 'limitRecord') {
        this.$refs.limitRecord.getTableData()
      }else {
        this.$refs.memberRecord.initRecord()
      }
    },
    async initBanner() {
      try {
        const count = await getSystemViewLayout()
        this.bannerState.taskLayout = count?.baseLayout || 2
        this.formCellCount = count?.formCellCount || 1
      } catch (error) {
        console.warn(error, 'error try catch initBanner');
      }
      // 通栏模式tabPosition默认left
      if (this.bannerState.taskLayout === 1) {
        this.bannerState.tabPosition = 'left'
      }
      let leftTabBarList = [
        { position: 'left', tabLabel:this.$t('member.components.title46'), tabName: 'member-info', tabShow: true}, // 会员信息
      ]
      let rightTabBarList = [
        { position: 'right', tabLabel:this.$t('common.base.dynamicInfo'), tabName: 'record', tabShow: true, disabled: true}, // 动态信息
        { position: 'right', tabLabel:this.$t('common.member.point'), tabName: 'pointRecord', tabShow: true}, // 会员积分
        { position: 'right', tabLabel:this.$t('common.member.balance'), tabName: 'balanceRecord', tabShow: true}, // 会员钱包
        { position: 'right', tabLabel:this.$t('member.detail.title23'), tabName: 'limitRecord', tabShow: true}, // 额度记录
        { position: 'right', tabLabel:this.$t('member.detail.title17'), tabName: 'serviceFeeRecord', tabShow: true}, // 服务费记录
      ]
      // 过滤掉会员积分
      if (!this.pointsEnable) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='pointRecord')
      }
      // 过滤掉会员钱包
      if (!this.balanceEnable) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='balanceRecord')
      }
      // 过滤掉额度记录
      if (!this.quotaEnable) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='limitRecord')
      }
      // 过滤掉服务费记录
      if (!this.serviceFeeEnable) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='serviceFeeRecord')
      }
      // 读取缓存tabbar修改右栏tabbar配置
      try {
        let { TabBarListItemKey:tabName, TabBarListItemShow:tabShow} = BaseTabBarUsualEnum;
        let parasm_ = {
          equipment:StorageHttpParamsForTerminalType.PC,
          bizType:StorageHttpParamsForModuleType.Task,
          bizTypeId:`member_${this.memberId}`
        }
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(parasm_);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        rightTabBarList = computedTabList(rightTabBarList, storageList_)
        console.log(rightTabBarList, 'rightTabBarList');
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }

      this.bannerState.leftActiveTab = leftTabBarList[0].tabName
      this.bannerState.leftActiveTabItem = leftTabBarList[0]
      this.bannerState.leftTabBarList = leftTabBarList
      this.bannerState.rightActiveTab = rightTabBarList[0].tabName
      this.bannerState.rightActiveTabItem = rightTabBarList[0]
      this.bannerState.rightTabBarList = rightTabBarList
    },
    tabBarChangeItem (item) {
      let { TabBarListItemKey:tabName } = BaseTabBarUsualEnum;
      let { position } = item
      this.bannerState.tabPosition = position
      // 通栏导航和左侧导航共用leftActiveTab数据
      if (this.bannerState.taskLayout === 1 || position == 'left') {
        this.bannerState.leftActiveTab = item[tabName];
        this.bannerState.leftActiveTabItem = item
      }
      // 右侧导航
      if (position == 'right') {
        this.bannerState.rightActiveTab = item[tabName];
        this.bannerState.rightActiveTabItem = item
        // 原el-table点击回调
        this.$nextTick(()=>{
          this.handleClick(item)
        })
      }
    },
    tabBarUpdateList(list) {
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let params = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Task,
        bizTypeId:`member_${this.memberId}`,
        cardList:list_
      }
      // 存储右栏tabbar
      setStorageForDetailTabbar(params)
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeTaskDetailLayout(type, columns) {
      this.bannerState.leftActiveTab = this.bannerState.leftTabBarList[0].tabName
      this.bannerState.leftActiveTabItem = this.bannerState.leftTabBarList[0] 
      this.bannerState.taskLayout = type
      this.bannerState.tabPosition = 'left'
      if (type === 2) {
        this.bannerState.rightActiveTab = this.bannerState.rightTabBarList[0].tabName
        this.bannerState.rightActiveTabItem = this.bannerState.rightTabBarList[0]
      }
      this.formCellCount = columns * 1
    }
  },
  watch: {
    collapseDirection(newValue) {
      sessionStorage.setItem(
        `member_collapseDirection_${this.memberId}`,
        newValue
      );
    },
    "bannerState.leftTabBarList": {
      handler() {
        this.bannerState.taskLayoutTabBarList = cloneDeep([...this.bannerState.leftTabBarList,...this.bannerState.rightTabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
    "bannerState.rightTabBarList": {
      handler() {
        this.bannerState.taskLayoutTabBarList = cloneDeep([...this.bannerState.leftTabBarList,...this.bannerState.rightTabBarList].filter(item => item.tabShow));
      },
      deep: true
    },
  },
};
</script>

<style lang="scss" scoped>
.task-detail-container {
  height: 100%;
  padding: 12px;
  display: flex;
  flex-direction: column;
  .task-detail-header {
  min-height: 56px;
  padding: 12px 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  .el-button {
      margin-left: 12px;
    }
  }
  .detail-main-content {
    height: auto !important;
    min-height: auto !important;
    flex: 1 !important;
    .task-detail-main-content-right {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
